<?php

require_once($GLOBALS['BIB'] . "/Objects/obj.files.mex");
if (isset($_POST['ID'])) {
    $_GET['ID'] = $_POST['ID'];
}
if (isset($_POST['CID'])) {
    $_GET['CID'] = $_POST['CID'];
}
if (isset($_POST['Target'])) {
    $_GET['Target'] = $_POST['Target'];
}

if (isset($_FILES['FILE']) && $_FILES['FILE'] != '') {

    $prefix = $_GET['ID'];

    $file = $_FILES['FILE'];
    $ext = '';
    $FName = strtolower($_FILES['FILE']['name']);
    $ExtExt = explode(".", $FName);
    $ExtExtC = count($ExtExt) - 1;
    $ExtExt = $ExtExt[$ExtExtC];
    $prefix = md5($prefix);
    $dir = $GLOBALS['DOC'] . 'PRFLDOCS/' . $_GET['CID'] . '/';
    if (!file_exists($dir)) {
        mkdir($dir);
    }
    $ffile = $prefix . '.' . $ExtExt;
    if (isset($_POST['RNF'])) {
        $ffile = $prefix . '_' . $_POST['RNF'] . '.' . $ExtExt;
    }
    if (fileimport($file, $ext, $ffile, $dir) == true) {
        if (!isset($_POST['RNF'])) {
            $DC = $GLOBALS['MYT']->db_query("UPDATE hd_documentos SET FILE = '$ffile' WHERE dtd_ID = {$_GET['ID']}");
        }
        echo '<script charset="utf-8" type="text/javascript">';
        if ($_POST['Target'] != '') {
            echo 'document.getElementById(\'secdoc' . $_POST['Target'] . '\').innerHTML=\'OK - Guardado\';';
        }
        echo 'window.close();</script>';
    } else {
        echo 'Ocorreu um erro';
    }
}